﻿using System.Text.RegularExpressions;
using AntC.AspNetCore.ApiEncryption.Internal;
using AntC.AspNetCore.ApiEncryption.Internal.Interfaces;
using Microsoft.Extensions.Options;

namespace AntC.AspNetCore.ApiEncryption.PolicyProviders
{
    /// <summary>
    /// 接口地址URL正则匹配加密策略器
    /// <remarks>
    /// <![CDATA[
    /// 需要在appsetting配置文件中增加以下配置
    ///  "UrlRegexEncryptionPolicyOptions": {
    ///    "RequestPathRegex": "请求数据解密URL正则表达式",
    ///    "ResponsePathRegex": "响应数据加密URL正则表达式" 
    ///  }
    ///
    /// 并在Startup.ConfigureServices方法中配置
    ///   var serviceProvider = services.BuildServiceProvider();
    ///   IConfiguration configuration = serviceProvider.GetService<IConfiguration>();
    ///   services.Configure<UrlRegexEncryptionPolicyOptions>(configuration.GetSection("UrlRegexEncryptionPolicyOptions"));
    /// ]]>
    /// </remarks>
    /// </summary>
    public class UrlRegexEncryptionPolicyProvider : IApiEncryptionPolicyProvider
    {
        private readonly IOptionsSnapshot<UrlRegexEncryptionPolicyOptions> _options;

        public UrlRegexEncryptionPolicyProvider(IOptionsSnapshot<UrlRegexEncryptionPolicyOptions> options)
        {
            _options = options;
        }

        /// <summary>
        /// 当前请求是否要提供接口数据解密功能
        /// </summary>
        /// <param name="context">上下文</param>
        /// <returns></returns>
        public bool IsDecryptCurrentRequest(ApiEncryptionContext context) => Regex.IsMatch(context.HttpContext.Request.Path.ToString(), _options?.Value?.RequestPathRegex ?? ".*");

        /// <summary>
        /// 当前响应是否要提供接口数据加密功能
        /// </summary>
        /// <param name="context">上下文</param>
        /// <returns></returns>
        public bool IsEncryptCurrentResponse(ApiEncryptionContext context) => Regex.IsMatch(context.HttpContext.Request.Path.ToString(), _options?.Value?.ResponsePathRegex ?? ".*");
    }
}
